package com.tbb.app.base.service.impl;

import com.tbb.app.base.service.IFileService;
import com.tbb.app.common.config.CustomProps;
import com.tbb.app.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements IFileService {

    @Autowired
    private CustomProps customProps;

    @Override
    public String upload(MultipartFile file) {
        //获取文件的原始名称
        String originalFilename = file.getOriginalFilename();
        //获取最后一个.的位置
        assert originalFilename != null;
        int lastIndexOf = originalFilename.lastIndexOf(".");
        //获取文件的后缀名
        String suffix = originalFilename.substring(lastIndexOf);
        String fileName = UUID.randomUUID() + suffix;
        File folder = new File(customProps.getFilePath());
        if(!folder.exists()){
            folder.mkdirs();
        }
        File localFile = new File(customProps.getFilePath(), fileName);
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            log.error("IOE", e);
            throw new BusinessException("文件上传失败");
        }
        return "http://" + customProps.getFileServer() + customProps.getFileUrl() + fileName;
    }
}
